package com.tdam2011.grupo02.ui;

import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.compatibility.ActionBarFragmentActivity;
import com.tdam2011.grupo02.data.LogsController;
import com.tdam2011.grupo02.support.PagerAdapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;

public class MensajeriaWebFragmentActivity extends ActionBarFragmentActivity
		implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener,
		ContactDataInterface {

	private TabHost mTabHost;
	private ViewPager mViewPager;
	private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, MensajeriaWebFragmentActivity.TabInfo>();
	private PagerAdapter mPagerAdapter;
	public static String idContacto;

	private static final int ID_MOBILE_CONNECTION = 1;
	private static final int ID_NO_CONNECTION = 2;
	private String notificacion;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mensajeweb_bandejas);

		setTitle(R.string.msgWebTitle);

		intialiseViewPager();
		initialiseTabHost(savedInstanceState);

		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
		}
	}

	private class TabInfo {
		private String tag;
		private Class<?> clss;
		private Bundle args;
		private Fragment fragment;

		TabInfo(String tag, Class<?> clazz, Bundle args) {
			this.tag = tag;
			this.clss = clazz;
			this.args = args;
		}
	}

	/**
	 * A simple factory that returns dummy views to the Tabhost
	 */
	class TabFactory implements TabContentFactory {

		private final Context mContext;

		public TabFactory(Context context) {
			mContext = context;
		}

		public View createTabContent(String tag) {
			View v = new View(mContext);
			v.setMinimumWidth(0);
			v.setMinimumHeight(0);
			return v;
		}
	}

	private static View createTabView(final Context context, final String text) {
		View view = LayoutInflater.from(context).inflate(
				R.layout.tab_indicator_contactdroid, null);
		TextView tv = (TextView) view.findViewById(R.id.tabsText);
		tv.setText(text);
		return view;
	}

	/**
	 * Initialise ViewPager
	 */
	private void intialiseViewPager() {
		List<Fragment> fragments = new Vector<Fragment>();

		fragments.add(Fragment.instantiate(this,
				WebMessageLogListFragment.class.getName()));
		fragments.add(Fragment.instantiate(this,
				BandejaSalidaListFragment.class.getName()));

		mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(),
				fragments);

		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mViewPager.setAdapter(this.mPagerAdapter);
		mViewPager.setOnPageChangeListener(this);
	}

	/**
	 * Initialise the Tab Host
	 */
	private void initialiseTabHost(Bundle args) {
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
		TabInfo tabInfo = null;

		String tabConversation = getString(R.string.tabConversation);
		String tabBandejaSalida = getString(R.string.tabBandejaSalida);

		AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(tabConversation)
				.setIndicator(tabConversation), (tabInfo = new TabInfo(
				tabConversation, WebMessageLogListFragment.class, args)));
		mapTabInfo.put(tabInfo.tag, tabInfo);

		AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(tabBandejaSalida)
				.setIndicator(tabBandejaSalida), (tabInfo = new TabInfo(
				tabBandejaSalida, BandejaSalidaListFragment.class, args)));
		mapTabInfo.put(tabInfo.tag, tabInfo);

		onTabChanged(tabConversation);

		mTabHost.setOnTabChangedListener(this);
	}

	/**
	 * Add Tab content to the Tabhost
	 * 
	 * @param activity
	 * @param tabHost
	 * @param tabSpec
	 * @param clss
	 * @param args
	 */
	private static void AddTab(MensajeriaWebFragmentActivity activity,
			TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
		View tabview = createTabView(tabHost.getContext(), tabInfo.tag);

		tabSpec.setIndicator(tabview).setContent(
				activity.new TabFactory(activity));
		tabHost.addTab(tabSpec);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int position) {
		mTabHost.setCurrentTab(position);
	}

	@Override
	public void onTabChanged(String arg0) {
		int pos = mTabHost.getCurrentTab();
		mViewPager.setCurrentItem(pos);
	}

	private void sendMsgWeb() {
			Intent intent = new Intent(MensajeriaWebFragmentActivity.this,
					MensajeWebComposicionActivity.class);
			startActivity(intent);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		if (id == ID_MOBILE_CONNECTION) {
			dialog = createMobileConnectionDialog();
		} else if (id == ID_NO_CONNECTION) {
			dialog = createNoConnectionDialog();
		} else {
			dialog = super.onCreateDialog(id);
		}
		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	}

	private Dialog createMobileConnectionDialog() {
		OnClickListener clickOk = new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(MensajeriaWebFragmentActivity.this,
						MensajeWebComposicionActivity.class);
				startActivity(intent);
			}
		};

		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.quick_action_msgweb)
				.setTitle(getString(R.string.connectionDialogTitle))
				.setPositiveButton(getString(R.string.alertBtnOk),
						clickOk)
				.setNegativeButton(getString(R.string.alertBtnCancel),
						null).setMessage(notificacion).create();
		return dialog;
	}

	private Dialog createNoConnectionDialog() {
		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.quick_action_msgweb)
				.setTitle(getString(R.string.connectionDialogTitle))
				.setPositiveButton(getString(R.string.alertBtnOk),
						null).setMessage(notificacion).create();
		return dialog;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu_web_messages, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
		case R.id.menu_msgw_edit:
			sendMsgWeb();
			break;
		case R.id.menu_settings:
			Intent intent = new Intent(this,
					MsgwLogPreferences.class);
			startActivity(intent);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public String[] onDataSelected() {
		idContacto = LogsController.CONTACTS_ALL;
		String[] data = new String[2];

		String nombreContacto = ContactsManagerSingleton.getInstance(this)
				.getContactsManager().getContactNameById(idContacto);

		data[0] = idContacto;
		data[1] = nombreContacto;

		return data;
	}
}
